<template>
  <a-modal
    :open="open"
    width="860px"
    title="新增科室级仓库"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <div>
      <BaseTable
        v-model:expanded-row-keys="expandedRowKeys"
        :data-source="tableData"
        fill
        :extra-height="300"
        row-key="id"
        :custom-row="(record) => ({ onClick: () => onSelectRow(record, 1) })"
        :row-class-name="(record) => (record.id === selectRow.id ? 'selected-row' : '')"
        :loading="loading"
        :scroll="{ x: 600 }"
        :columns="columns"
      >
        <template #expandIcon="{ expanded, record, onExpand }">
          <component
            :is="Icon[expanded ? 'CaretDownOutlined' : 'CaretRightOutlined']"
            v-if="record.children?.length"
            class="px-1"
            @click="onExpand(record, $event)"
          />
        </template>
      </BaseTable>
    </div>
  </a-modal>
</template>
<script setup>
import { message } from 'ant-design-vue'
import * as Icon from '@ant-design/icons-vue'

const emit = defineEmits(['update:open', 'update:value', 'success'])

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  }
})
const loading = ref(false)
const tableData = ref([])
const expandedRowKeys = ref([])
const selectRow = ref({})
const columns = ref([
  { title: '科室名称', dataIndex: 'ksmc' },
  { title: '助记码', dataIndex: 'pyjm' },
  { title: '科室编号', dataIndex: 'ksdm' },
  { title: '科室地点', dataIndex: 'gzdd' }
])

const getData = async () => {
  loading.value = true
  const { code, data, msg } = await post('/operation/opex/getDeptInfoList', { yxzt: '0' })
  loading.value = false
  if (code !== 0) return message.error(msg || '获取科室失败')
  tableData.value = data || []
}
const onOk = async () => {
  const { code, msg } = await post('/operation/opex/doSaveDepartmentLevelWareHouseInfo', {
    ckid: selectRow.value.ksdm
  })
  if (code !== 0) return message.error(msg || '保存失败')
  message.success(msg || '保存失败')
  reset()
  emit('update:open', false)
  emit('success')
}
const onSelectRow = (select) => {
  selectRow.value = select
}

const isCompleted = computed(() => {
  return selectRow.value.id
})
watch(
  () => props.open,
  (val) => {
    if (val) {
      getData()
    }
  }
)
const reset = () => {
  selectRow.value = {}
}

const onCancel = () => {
  reset()
  emit('update:open', false)
}
</script>
<style lang="less" scoped></style>
